package data

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"gorm_transaction/internal/biz"
)

type cellRepo struct {
	data *Data
	log  *log.Helper
}

func NewCellRepo(data *Data, logger log.Logger) biz.CellBizInterface {
	return &cellRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

func (c *cellRepo) CellFindOneById(ctx context.Context, id uint32) (*biz.Cell, error) {

	db := c.data.Mysql.Table(biz.CellTableName).WithContext(ctx)

	cellModel := &biz.Cell{}
	errTake := db.Where("id = ?", id).Take(cellModel).Error

	return cellModel, errTake
}

// 一个父级cell可能有多个子cell
func (c *cellRepo) CellFindManyByParentId(ctx context.Context, parentId uint32) ([]*biz.Cell, error) {

	db := c.data.Mysql.Table(biz.CellTableName).WithContext(ctx)

	cellModels := make([]*biz.Cell, 0)
	errTake := db.Where("parent_id = ?", parentId).Find(&cellModels).Error

	return cellModels, errTake
}

func (c *cellRepo) RecursionGetParents(ctx context.Context, id uint32) ([]*biz.Cell, error) {

	cells := make([]*biz.Cell, 0)

	// 查当前cell
	currCell, errCurrCell := c.CellFindOneById(ctx, id)
	if errCurrCell != nil {
		return nil, errCurrCell
	}
	// 当前cell放入结果中
	cells = append(cells, currCell)

	// Notice 递归结束的条件～有父级事件的话 递归获取～业务中规定: parent_id 为0的数据是"元数据"～
	if currCell.ParentId != 0 {
		currId := currCell.ParentId
		// 递归
		currCellRe, errCurrCellRe := c.RecursionGetParents(ctx, currId)
		if errCurrCellRe != nil {
			// Notice 这里看实际业务需求，递归的时候如果发生错误返回已经拿到的结果就好了
			return cells, nil
		}
		// 注意这里的写法
		return append(cells, currCellRe...), nil
	}

	return cells, nil
}
